package com.qf.web.controller;/**
 * @author Administrator
 * @version v1.0
 * @date 2022/4/21
 */

import com.alibaba.fastjson.JSON;
import com.qf.domain.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * projectName:Project_2202
 * author:
 * time:2022/4/21 12:47
 * description:
 */
@WebServlet("/searchUser")
public class SearchUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        String username = request.getParameter("username");
        String gender = request.getParameter("gender");
        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> params = new ArrayList<>();
        if(!StringUtils.isEmpty(username)){
            where.append(" AND username LIKE ? ");
            params.add("%"+username+"%");
        }
        if(!StringUtils.isEmpty(gender)){
            where.append(" AND gender = ? ");
            params.add(gender);
        }
        UserService userService = new UserServiceImpl();
        List<User>  users =  userService.findUsersAny(where.toString(),params);
        if(users!=null || users.size()>0){
            String jsonString = JSON.toJSONString(users);
            response.getWriter().print(jsonString);
        }else{
            response.getWriter().write(0);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}